<template>
	<view class="page-container">

		<view class="content-wrapper">
			<!-- 创建方式选择 -->
			<view class="create-type-selector mb-30">
				<view class="type-item" :class="{'active': createType === 'manual'}"
					@click="switchCreateType('manual')">
					手动创建
				</view>
				<view class="type-item" :class="{'active': createType === 'wechat'}"
					@click="switchCreateType('wechat')">
					公众号导入
				</view>
			</view>
			<view class="create-type-hint" v-if="createType === 'manual'">
				可以自由编辑文章内容和排版
			</view>
			<view class="create-type-hint" v-if="createType === 'wechat'">
				一键导入微信公众号文章，快速发布
			</view>

			<!-- 封面图预览区域 -->
			<view v-show="imgUrl" class="cover-preview-wrapper">
				<view class="cover-preview-container">
					<image class="cover-image" :src="imgUrl" mode="aspectFill" @click="preViewImg"></image>
					<text @click="deleteImg" class="iconfont icon-guanbi1 cover-delete-btn"></text>
				</view>
			</view>

			<!-- 标题区域 -->
			<view class="mt-20" v-if="createType === 'manual' || (createType === 'wechat' && form.title)">
				<input maxlength="40" placeholder="请输入标题" v-model="form.title" />
			</view>
			<view class="mt-30 mb-30" v-if="createType === 'manual' || (createType === 'wechat' && form.title)"
				style="width: 98%;height: 1rpx;background-color: #ECECEC;"></view>

			<!-- 内容区域容器 -->
			<view class="content-area">
				<!-- 手动创建内容区域 -->
				<cu-editor v-if="createType === 'manual'" ref="editor" :content="form.content" :bottomBarHeight="100"
					@toolbarChange="onEditorToolbarChange"></cu-editor>

				<!-- 公众号导入区域 -->
				<view v-if="createType === 'wechat'" class="wechat-import-container">
					<view class="wechat-input-box mb-20">
						<input class="wechat-url-input" clearable v-model="wechatArticleUrl" placeholder="请输入公众号文章链接" @input="handleUrlInput" />
						<button class="import-btn" style="color: white;" @click="importWechatArticle">一键导入</button>
					</view>
					<view class="c-666 fs-28 mb-10 c-red" v-if="!importSuccess">
						说明：如何获取链接；打开需要导入的文章，按照图片示例，获取链接，放入输入框里面
					</view>
					<view class="c-666 fs-28 mb-10 c-green" v-else>
						导入成功！您可以预览并编辑文章内容
					</view>
					<image :class="[importSuccess ? 'success-image' : 'wechat-guide-image']" :src="importSuccess ? 'https://yjgs.jsonbug.com/test/wenxdaoru.png' : 'https://yjgs.jsonbug.com/test/wx_import.png'" mode="widthFix">
					</image>
				</view>
			</view>
		</view>

		<view style="height: 200rpx;"></view>

		<!-- 底部工具栏 -->
		<view v-if="!editorToolbarShow" class="box-btn-send">
			<view class="flex ac">
				<view @click.stop="uploadImg" class="flex ac fc jc ml-30">
					<view>
						<text class="iconfont icon-xiangji "></text>
					</view>
					<view class="fs-26">
						{{imgUrl ? '更换封面' : '封面图'}}
					</view>
				</view>
				<view v-if="!form.inputLabel" @click="openPopup" class="flex ac fc jc ml-30">
					<view>
						<text class="iconfont-yjgs">&#xe886;</text>
					</view>
					<view class="fs-26">标签</view>
				</view>
				<view v-else class="ml-30 pos-r">
					<view @click="openPopup" class="box-item-pop">
						{{form.inputLabel || ''}}
					</view>
					<text @click.stop="deleteLabel" class="iconfont icon-guanbi1 pos-a box-fom-close"
						style="font-size: 40rpx;top: -15rpx;"></text>
				</view>
			</view>
			<view class="flex ac">
				<view @click="sendSubmit(4)" class="box-btn-submit mr-20" style="background-color: #F9BC11;"
					:class="{'btn-disabled': loading}">
					{{loading ? '提交中...' : '暂存'}}
				</view>
				<view @click="sendSubmit(2)" class="box-btn-submit mr-20" :class="{'btn-disabled': loading}">
					{{loading ? '提交中...' : '发布'}}
				</view>
			</view>
		</view>

		<!-- 弹出层 -->
		<uni-popup ref="popup" background-color="rgba(0,0,0,0)" :safeArea="true">
			<view class="box-popup">
				<view class="input-container">
					<input v-model="form.inputLabel" class="label-input" placeholder="请输入标签" maxlength="10" />
					<view class="btn-container">
						<view @click="cancelInput" class="btn btn-cancel">取消</view>
						<view @click="confirmInput" class="btn btn-confirm">确认</view>
					</view>
				</view>
			</view>
		</uni-popup>

	</view>
</template>

<script>
	import cuEditor from '@/pages/extend/components/cu-editor/cu-editor'
	import dragImage from '@/pages/extend/components/shmily-drag-image/components/shmily-drag-image/shmily-drag-image.vue'
	import {
		UserArticleSave,
		UserArticleDetail,
		parseWechatArticle
	} from "@/api/extend";
	export default {
		components: {
			dragImage,
			cuEditor
		},
		data() {
			return {
				options: {},
				imgUrl: '',
				form: {
					title: '',
					content: '',
					inputLabel: ''
				},
				loading: false,
				editorReady: false,
				editorToolbarShow: false,
				createType: 'manual', // 创建方式：manual-手动创建，wechat-公众号导入
				wechatArticleUrl: '', // 公众号文章链接
				importSuccess: false, // 添加导入成功状态标记
				originalWechatUrl: '', // 保存原始导入成功的链接
			}
		},
		onLoad(options) {
			this.options = options;
			if (options.id) {
				this.UserArticleDetailFunc();
			}
		},
		onReady() {
			// 标记编辑器已准备就绪
			this.editorReady = true;

			// 如果已经有内容，设置到编辑器
			if (this.form.content && this.$refs.editor) {
				this.setEditorContent();
			}

		},
		watch: {
			// 监听content变化，当内容变化且编辑器就绪时设置内容
			'form.content': function(newVal) {
				if (newVal && this.editorReady && this.$refs.editor) {
					this.setEditorContent();
				}
			}
		},
		methods: {
			// 切换创建方式
			switchCreateType(type) {
				// 保存当前的封面图状态
				const currentImgUrl = this.imgUrl;

				this.createType = type;
				// 切换时重置相关数据
				if (type === 'wechat') {
					this.wechatArticleUrl = '';
					this.importSuccess = false; // 重置导入状态
					this.originalWechatUrl = ''; // 重置原始链接
				} else {
					if (this.editorReady && this.$refs.editor) {
						this.setEditorContent();
					}
				}

				// 确保封面图状态保持不变
				this.$nextTick(() => {
					this.imgUrl = currentImgUrl;
				});
			},

			// 导入公众号文章
			async importWechatArticle() {
				if (!this.wechatArticleUrl) {
					uni.showToast({
						title: '请输入公众号文章链接',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '导入中...'
				});

				try {
					// TODO: 这里需要调用后端API进行文章导入
					const res = await parseWechatArticle({
						url: this.wechatArticleUrl
					});
					this.form.title = res.data.title;
					this.imgUrl = res.data.cover_url;
					this.importSuccess = true; // 标记导入成功
					this.originalWechatUrl = this.wechatArticleUrl; // 保存成功导入的链接
					uni.showToast({
						title: '导入成功',
						icon: 'success'
					});
				} catch (error) {
					this.importSuccess = false; // 导入失败，确保状态正确
					this.originalWechatUrl = ''; // 重置原始链接
					uni.showToast({
						title: error,
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			// 封装设置编辑器内容的方法
			setEditorContent() {
				if (!this.$refs.editor || !this.form.content) return;

				setTimeout(() => {
					// 确保内容是字符串类型
					let content = this.form.content;
					if (typeof content !== 'string') {
						content = String(content);
					}

					this.$refs.editor.setValue(content);
				}, 300);
			},
			onBlur() {
				this.showBtn = true;

				// 滚动到正常视图位置，确保底部按钮可见
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 0,
						duration: 100
					});
				}, 200);
			},
			onFocus() {
				this.showBtn = false;

				// 简化处理，不做额外滚动操作
				// 编辑器内部已经自己处理光标可见性
			},

			async UserArticleDetailFunc() {
				uni.showLoading({
					title: '加载中...'
				});

				try {
					const res = await UserArticleDetail({
						id: this.options.id
					});

					let row = res.data;

					// 确保content字段有值
					let content = row.content || row.text || '';

					this.form = {
						id: row.id,
						title: row.title || '',
						content: content,
						inputLabel: row.label || ''
					};
					this.imgUrl = row.cover;
					
					if(row.wx_url){
						this.createType = 'wechat';
						this.wechatArticleUrl = row.wx_url;
						this.originalWechatUrl = row.wx_url; // 保存原始链接
						this.importSuccess = true; // 如果有wx_url，说明已经导入成功
					}else{
						this.createType = 'manual';
					}

					// 如果编辑器已经准备好，立即设置内容
					if (this.editorReady && this.$refs.editor) {
						this.setEditorContent();
					}

				} catch (error) {
					uni.showToast({
						title: '获取详情失败: ' + error,
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},

			deleteLabel() {
				this.form.inputLabel = null;
			},
			cancelInput() {
				this.form.inputLabel = '';
				this.$refs.popup.close();
			},
			confirmInput() {
				if (!this.form.inputLabel) {
					uni.showToast({
						title: '请输入标签内容',
						icon: 'none'
					})
					return;
				}
				this.form.inputLabel = this.form.inputLabel;
				this.$refs.popup.close();
			},
			async sendSubmit(type) {
				if (this.loading) return;

				// 表单验证
				if (!this.form.title) {
					uni.showToast({
						title: '请输入标题',
						icon: 'none'
					});
					return;
				}

				if (!this.form.inputLabel) {
					uni.showToast({
						title: '请输入标签',
						icon: 'none'
					});
					this.openPopup();
					return;
				}

				if (!this.imgUrl) {
					uni.showToast({
						title: '请上传封面图',
						icon: 'none'
					});
					return;
				}

				// 检查公众号模式下链接是否有变更但未重新导入
				if (this.createType === 'wechat') {
					if (!this.wechatArticleUrl) {
						uni.showToast({
							title: '请输入公众号文章地址',
							icon: 'none'
						});
						return;
					}
					
					// 检查链接是否已变更但未重新导入
					if (this.wechatArticleUrl !== this.originalWechatUrl || !this.importSuccess) {
						uni.showToast({
							title: '链接已变更，请重新导入文章',
							icon: 'none',
							duration: 2000
						});
						return;
					}
				}

				if (this.createType == 'manual') {
					// 获取编辑器内容
					try {
						// 先检查内容是否为空
						const isEmpty = await this.$refs.editor.isContentEmpty();
						if (isEmpty) {
							uni.showToast({
								title: '内容不能为空',
								icon: 'none'
							});
							return;
						}

						// 获取编辑器内容
						const editorContent = await this.$refs.editor.getContent();
						this.form.content = editorContent.html;
					} catch (err) {
						uni.showToast({
							title: '获取编辑器内容失败: ' + err,
							icon: 'none'
						});
						return;
					}
				}

				// 保存数据
				this.loading = true;
				try {
					const res = await UserArticleSave({
						id: this.options.id, // 新闻ID
						status: type,
						title: this.form.title,
						text: this.form.content,
						label: this.form.inputLabel,
						cover: this.imgUrl,
						wx_url: this.wechatArticleUrl
					});
					uni.showToast({
						title: res.message,
						icon: 'none',
					});

					if (res.status == 200) {
						setTimeout(() => {
							uni.navigateBack();
						}, 2000);
					}
				} catch (err) {
					uni.showToast({
						title: err,
						icon: 'none',
					});
				} finally {
					this.loading = false;
				}
			},

			deleteImg() {
				this.imgUrl = '';
				this.importSuccess = false;
				uni.showToast({
					title: '封面图已删除',
					icon: 'none'
				});
			},
			preViewImg() {
				if (this.imgUrl) {
					uni.previewImage({
						urls: [this.imgUrl],
						current: 0
					});
				}
			},
			uploadImg() {
				this.$util.uploadImageOne({
					url: 'upload/image',
					count: 1
				}, (res) => {
					this.imgUrl = res.data.path;
					uni.showToast({
						title: '封面图上传成功',
						icon: 'none'
					});
				});
			},
			openPopup() {
				this.$refs.popup.open('bottom')
			},
			// 监听编辑器工具栏状态变化
			onEditorToolbarChange(show) {
				this.editorToolbarShow = show;
			},
			handleUrlInput() {
				// 如果当前链接和成功导入时的链接不同，则重置导入状态
				if (this.importSuccess && this.wechatArticleUrl !== this.originalWechatUrl) {
					this.importSuccess = false;
					uni.showToast({
						title: '链接已变更，请重新导入',
						icon: 'none'
					});
				}
				
				// 如果用户删除了URL，恢复到初始状态
				if (!this.wechatArticleUrl || this.wechatArticleUrl.trim() === '') {
					this.importSuccess = false;
					this.form.title = '';
					this.imgUrl = '';
					this.originalWechatUrl = '';
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.page-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #FFFFFF;
	}

	.content-wrapper {
		flex: 1;
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		overflow-y: auto;
		-webkit-overflow-scrolling: touch;
		position: relative;
	}

	.editor-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		min-height: 0;
	}

	.box-main {
		box-sizing: border-box;
		height: 100vh;
		background-color: #FFFFFF;
		position: relative;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}

	.main-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		padding: 20rpx;
		padding-bottom: 200rpx;
		overflow: hidden;
	}

	.editor-bottom-indicator {
		width: 100%;
		height: 2rpx;
		background-color: #ECECEC;
		margin-top: 10rpx;
		margin-bottom: 10rpx;
	}

	.box-upload {
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		width: 204rpx;
		height: 204rpx;
		border: 1rpx solid #808080;
		border-radius: 20rpx;
	}

	.cover-preview-wrapper {
		width: 100%;
		margin-bottom: 30rpx;
		z-index: 2;
	}

	.cover-preview-container {
		position: relative;
		width: 240rpx;
		height: 180rpx;
		border-radius: 12rpx;
		overflow: hidden;
		border: 1px solid #ECECEC;
		background-color: #fff;
	}

	.cover-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
		display: block;
	}

	.content-area {
		flex: 1;
		position: relative;
		z-index: 1;
	}

	.cover-delete-btn {
		position: absolute;
		top: 10rpx;
		right: 10rpx;
		width: 40rpx;
		height: 40rpx;
		line-height: 40rpx;
		text-align: center;
		background-color: rgba(0, 0, 0, 0.5);
		color: #FFFFFF;
		border-radius: 50%;
		font-size: 24rpx;
		z-index: 10;
		cursor: pointer;
	}

	.box-item-pop {
		border-radius: 40rpx;
		line-height: 60rpx;
		height: 60rpx;
		width: fit-content;
		font-size: 26rpx;
		padding-left: 30rpx;
		padding-right: 30rpx;
		color: #2965FF;
		background-color: rgba(77, 126, 251, .25);
	}

	.box-popup {
		border-radius: 18rpx;
		overflow: hidden;
		padding: 30rpx;
		box-sizing: border-box;
		background-color: #FFFFFF;
		height: 36vh;
		width: 100%;
	}

	.box-btn-submit:active {
		opacity: .5;
	}

	.box-btn-submit {
		box-sizing: border-box;
		text-align: center;
		line-height: 60rpx;
		border-radius: 40rpx;
		width: 120rpx;
		height: 60rpx;
		background-color: #000000;
		color: white;
	}

	.box-btn-send {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		box-sizing: border-box;
		border-top: 1px solid #F3F3F3;
		z-index: 9999;
		box-shadow: 1px -3px 20rpx rgba(0, 0, 0, .12), 0 0 3rpx rgba(0, 0, 0, .04);
		color: #292929;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: #FFFFFF;
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		min-height: calc(80rpx + env(safe-area-inset-bottom));
	}

	.box-fom-close {
		top: -23rpx;
		right: -16rpx;
		position: absolute;
	}

	.box-for-img {
		display: grid;
		grid-template-columns: 1fr 1fr 1fr;
		grid-gap: 20rpx;
	}

	.input-container {
		padding: 30rpx;
	}

	.label-input {
		width: 100%;
		height: 80rpx;
		border: 1px solid #ECECEC;
		border-radius: 8rpx;
		padding: 0 20rpx;
		margin-bottom: 30rpx;
	}

	.btn-container {
		display: flex;
		justify-content: flex-end;
		gap: 20rpx;
	}

	.btn {
		padding: 20rpx 40rpx;
		border-radius: 8rpx;
		font-size: 28rpx;
	}

	.btn-cancel {
		background-color: #f5f5f5;
		color: #666;
	}

	.btn-confirm {
		background-color: #2965FF;
		color: white;
	}

	.btn-disabled {
		opacity: 0.5;
		pointer-events: none;
	}

	.create-type-selector {
		display: flex;
		justify-content: center;
		gap: 20rpx;
		margin: 20rpx auto;
		width: 85%;
	}

	.type-item {
		flex: 1;
		padding: 20rpx 30rpx;
		border: 1rpx solid #E5E5E5;
		border-radius: 8rpx;
		font-size: 26rpx;
		color: #666;
		text-align: center;
		position: relative;
		background: #F8F8F8;
		transition: all 0.3s ease;
		
		&::before {
			font-family: "iconfont";
			margin-right: 8rpx;
			font-size: 28rpx;
			vertical-align: middle;
		}
		
		&:first-child::before {
			content: "\e6e5";
		}
		
		&:last-child::before {
			content: "\e619";
		}

		&.active {
			background: #2965FF;
			color: #FFFFFF;
			border-color: #2965FF;
			transform: translateY(-1rpx);
			box-shadow: 0 2rpx 8rpx rgba(41, 101, 255, 0.15);
			
			&::after {
				content: '';
				position: absolute;
				bottom: -6rpx;
				left: 50%;
				transform: translateX(-50%);
				width: 20rpx;
				height: 3rpx;
				background: #2965FF;
				border-radius: 2rpx;
			}
		}

		&:active {
			transform: scale(0.97);
		}
	}

	.create-type-hint {
		text-align: center;
		font-size: 22rpx;
		color: #999;
		margin: 10rpx 0 20rpx;
	}

	.wechat-import-container {
		margin-top: 30rpx;
		padding: 20rpx;
		border: 1px solid #ECECEC;
		border-radius: 8rpx;
	}

	.wechat-guide-image {
		width: 100%;
		height: auto;
		margin-bottom: 20rpx;
	}

	.wechat-input-box {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.wechat-url-input {
		width: 70%;
		height: 80rpx;
		border: 1px solid #ECECEC;
		border-radius: 8rpx;
		padding: 0 20rpx;
	}

	.import-btn {
		margin-left: 20rpx;
		width: 180rpx;
		height: 70rpx;
		background: linear-gradient(to right, #2965FF, #4C83FF);
		color: #FFFFFF;
		font-size: 28rpx;
		border-radius: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 6rpx 20rpx rgba(41, 101, 255, 0.2);
		transition: all 0.3s ease;
		border: none;

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 2rpx 10rpx rgba(41, 101, 255, 0.2);
		}

		&:disabled {
			background: #F5F5F5;
			color: #CCCCCC;
			box-shadow: none;
		}
	}

	.success-image {
		width: 50%;
		height: auto;
		margin: 20rpx auto;
		display: block;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
</style>